package com.b3rwyn.textbomber;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class B3rwynsTextBomberActivity extends Activity {
	private EditText numberField;
	private EditText countField;
	private EditText messageField;
	private Button sendButton;
	private Button contactsButton;
	private SmsManager smsmanager = SmsManager.getDefault();
	private Intent contactsIntent;
	private static final int PICK_CONTACT = 1;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		numberField = (EditText) findViewById(R.id.phoneNumberField);
		countField = (EditText) findViewById(R.id.messageNumberField);
		messageField = (EditText) findViewById(R.id.messageField);
		sendButton = (Button) findViewById(R.id.sendButton);
		contactsButton = (Button) findViewById(R.id.contactsButton);
		contactsIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
		
		sendButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sendMessage();
				resetDisplay();
				
			}
		});

		contactsButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(contactsIntent, PICK_CONTACT);
			}
		});
	}
	
	
	@Override  
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			boolean hasNumber = false;
			String name = "";
	        Uri contactData = data.getData();
	        Cursor c =  managedQuery(contactData, null, null, null, null);
	        if (c.moveToFirst()) {
	            name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
	        }
		    ContentResolver cr = getContentResolver();
		    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + name + "'", null, null);
		    if (cursor.moveToFirst()) {
		        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
		        Cursor phones = cr.query(Phone.CONTENT_URI, null,Phone.CONTACT_ID + " = " + contactId, null, null);
		        while (phones.moveToNext()) {
		        hasNumber = true;
		            String number = phones.getString(phones.getColumnIndexOrThrow(Phone.NUMBER));
		            numberField.setText(number);
		        }
		        phones.close();
		    }
		    cursor.close();
		    if(!hasNumber){
		    	numberField.setText("");
		    	Toast.makeText(getBaseContext(), "Selected contact does not have a phone number. Please select another contact.", Toast.LENGTH_LONG).show();
		    }
		}
    }
	
	//----------------------------------------------------------------------------------------------
	private void sendMessage() {
		String phoneNumber = "";
		int totalNumMessages = 0;
		String message = "";
		int thread1NumMessages = 0;
		int thread2NumMessages = 0;
		
		try {
			phoneNumber = numberField.getText().toString();
			totalNumMessages = Integer.parseInt(countField.getText().toString());
			message = messageField.getText().toString();
		} catch (Exception e) {
			Log.d("sendMessage", e.getMessage());
		}
		phoneNumber = stripNumberFields(phoneNumber);
		totalNumMessages = Integer.parseInt(stripNumberFields(""+totalNumMessages));
		if(totalNumMessages>100){
			totalNumMessages = 100;//Hard limit messages to 100
			Toast.makeText(getBaseContext(), "Sorry: We changed your number of messages to a max of 100", Toast.LENGTH_LONG).show();
		}
		
		if(totalNumMessages%2==0){
			thread1NumMessages = totalNumMessages / 2;
			thread2NumMessages = totalNumMessages / 2;
		} else {
			thread1NumMessages = totalNumMessages / 2;
			thread2NumMessages = (totalNumMessages / 2) + 1;
		}
		
		MyThread smsThread = new MyThread(phoneNumber,thread1NumMessages,message,smsmanager,getBaseContext(),0);
		MyThread smsThread2 = new MyThread(phoneNumber,thread2NumMessages,message,smsmanager,getBaseContext(),thread1NumMessages);
		
		smsThread.start();
		try {
			Thread.sleep(6000);
		} catch(InterruptedException e) {
			//Do nothing
		} 
		smsThread2.start();
		
		//-------------------Old SMS Code-------------------
		/* 
		if (phoneNumber.length() > 0 && message.length() > 0 && numMessages > 0) {
			for (int i = 0; i < numMessages; i++) {
				if (message.length() < 160 - 5 - Integer.toString(numMessages).length()) {					 
					String sendMessage = "(" + Integer.toString(i + 1) + "\\"+ numMessages + ") " + message;
					smsmanager.sendTextMessage(phoneNumber, null, sendMessage,null, null);
				} else {
					String sendMessage = "(" + Integer.toString(i + 1) + "\\"+ numMessages + ") " + message;
					smsmanager.sendMultipartTextMessage(phoneNumber, null,smsmanager.divideMessage(sendMessage), null, null);
				}
			}
		} else {
			Toast.makeText(getBaseContext(), "Please fill all the fields before sending.", Toast.LENGTH_SHORT).show();
		}*/
	}
	
	
	private String stripNumberFields(String inputNmber){
		int oldNumberLength = inputNmber.length();
		String[] invalidCharacters = {")", "(", "-", " ", "*", "#", "-", ".", "N", "n", ",", ";", "/", "\\", "+"};
		
		for(int i = 0; i < invalidCharacters.length;i++){
			while(inputNmber.contains(invalidCharacters[i]))
			{
				int index = inputNmber.indexOf(invalidCharacters[i]);
				if(index == 0){
					inputNmber = inputNmber.substring(index+1);
				} else if(index > 0 && index < oldNumberLength-1){
					String originalNumber = inputNmber;
					inputNmber = inputNmber.substring(0, index);
					inputNmber += originalNumber.substring(index+1);
				} else if(index >= oldNumberLength-1){
					inputNmber = inputNmber.substring(0, index);
				}
			}
		}
		return inputNmber;
	}
	
	
	private void resetDisplay() {
		numberField.setText("");
		countField.setText("");
		messageField.setText("");
	}
}




class MyThread extends Thread {
	private String phoneNumber = "";
	private int numMessages = 0;
	private String message = "";
	private SmsManager smsmanager = null;
	private Context contextBase = null;
	private int messageStartNumber = 0;
	
	public MyThread(String phoneNumber, int numMessages, String message, SmsManager smsmanager, Context contextBase, int messageStartNumber) {
		this.phoneNumber = phoneNumber;
		this.numMessages = numMessages;
		this.message = message;
		this.smsmanager = smsmanager;
		this.contextBase = contextBase;
		this.messageStartNumber = messageStartNumber;
	}
	
	public void run(){
		if (phoneNumber.length() > 0 && message.length() > 0 && numMessages > 0) {
			for (int i = 0; i < numMessages; i++) {
				if (message.length() < 160 - 5 - Integer.toString(numMessages).length()) {					 
					String sendMessage = "(" + Integer.toString(i + 1 + messageStartNumber) + "\\"+ numMessages + ") " + message;
					smsmanager.sendTextMessage(phoneNumber, null, sendMessage,null, null);
				} else {
					String sendMessage = "(" + Integer.toString(i + 1 + messageStartNumber) + "\\"+ numMessages + ") " + message;
					smsmanager.sendMultipartTextMessage(phoneNumber, null,smsmanager.divideMessage(sendMessage), null, null);
				}
			}
		} else {
			Toast.makeText(contextBase, "Please fill all the fields before sending.", Toast.LENGTH_SHORT).show();
		}
	}
	
	
}









